package com.ai_chat.sys.controller;

import com.ai_chat.common.util.AlipayUtil;
import com.ai_chat.common.util.JwtUtil;
import com.ai_chat.common.vo.CodeType;
import com.ai_chat.common.vo.Result;
import com.ai_chat.sys.entity.Payment;
import com.ai_chat.sys.entity.TokenPackage;
import com.ai_chat.sys.entity.User;
import com.ai_chat.sys.service.impl.PaymentServiceImpl;
import com.ai_chat.sys.service.impl.TokenPackageServiceImpl;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;


@RestController
@CrossOrigin
@RequestMapping("/payment")
public class PaymentController {

    @Autowired
    private PaymentServiceImpl paymentService;

    @Autowired
    private TokenPackageServiceImpl tokenPackageService;

    @Autowired
    private AlipayUtil alipayUtil;

    @Autowired
    private JwtUtil jwtUtil;

    //购买套餐
    @GetMapping("/pay")
    public Result<Map<String,Object>> pay(@RequestHeader("Authorization") String token, @RequestParam("tokenPackageId") Integer tokenPackageId){
        System.out.println("token:" + token);
        System.out.println("tokenPackageId:" + tokenPackageId);

        User user;
        try{
            user = jwtUtil.parseToken(token, User.class);
            System.out.println("call pay");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("error");
            //jwt解析失败，认为凭证失效，要求前端重新登录。
            return Result.fail(CodeType.TOKEN_EXPIRED_OR_INVALID);
        }

        //查询套餐
        TokenPackage tokenPackage =  tokenPackageService.getTokenPackageById(tokenPackageId);
        if(tokenPackage == null){
            return Result.fail(CodeType.INVALID_TOKEN_PACKAGE);
        }


        // 初始化SDK
        AlipayClient alipayClient = null;
        try {
            alipayClient = new DefaultAlipayClient(alipayUtil.getAlipayConfig());
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        // 构造请求参数以调用接口
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();

        // 设置订单标题
        model.setSubject(tokenPackage.getPackageName());
        // 设置订单总金额
        StringBuilder totalAmount = new StringBuilder();
        totalAmount.append(tokenPackage.getPackagePrice() / 100);
        totalAmount.append('.');
        totalAmount.append(tokenPackage.getPackagePrice() % 100);
        System.out.println("总金额：" + totalAmount.toString());
        model.setTotalAmount(totalAmount.toString());



        // 设置商户订单号
        UUID uuid = UUID.randomUUID();
        String prefix = tokenPackageId.toString().length() < 2 ? "0" + tokenPackageId.toString() : tokenPackageId.toString();
        String outTradeNo = prefix + uuid.toString().replace("-","");

        model.setOutTradeNo(outTradeNo);
        System.out.println("商户订单号:" + outTradeNo);

        // 设置产品码
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        // 设置请求后页面的集成方式
        model.setIntegrationType("PCWEB");


        //设置回传参数，用户id。
        try {
            model.setPassbackParams(URLEncoder.encode(user.getId().toString(),"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        request.setBizModel(model);
        // 支付宝回调通知接口
        request.setNotifyUrl(alipayUtil.getNotifyURL());
//        // 支付宝支付完成后自动跳转的页面
//        request.setReturnUrl("https://www.baidu.com");


        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(request, "POST");
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        String pageRedirectionData = response.getBody();
        System.out.println(pageRedirectionData);


        Map<String, Object> data = new HashMap<>();
        data.put("formHtml", pageRedirectionData);

        return Result.success(data);

    }

    @PostMapping("/notify")
    public void payNotify(@RequestParam("trade_status") String trade_status, @RequestParam("passback_params") String passback_params,@RequestParam("total_amount") String total_amount,@RequestParam("out_trade_no") String out_trade_no){
        if(trade_status.equals("TRADE_SUCCESS")){
            paymentService.payNotify(passback_params,total_amount,Integer.parseInt(out_trade_no.substring(0,2)),out_trade_no);
        }
    }

    @GetMapping("/getPaymentRecords")
    public Result<List<Map<String,Object>>> getPaymentRecords(@RequestHeader("Authorization") String token){
        User user;
        try{
            user = jwtUtil.parseToken(token, User.class);
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail(CodeType.TOKEN_EXPIRED_OR_INVALID);
        }

        List<Payment> paymentList = paymentService.getPaymentList(user.getId());

        List<TokenPackage> tokenPackageList = tokenPackageService.getAllTokenPackage();
        //构建套餐id和套餐的键值对，并放入map，方便后续使用
        Map<Integer,TokenPackage> tokenPackageMap = new HashMap<>();
        for(TokenPackage tokenPackage : tokenPackageList){
            tokenPackageMap.put(tokenPackage.getId(),tokenPackage);
        }

        List<Map<String, Object>> data = new ArrayList<>();
        for(Payment payment : paymentList){
            Map<String, Object> paymentMap = new HashMap<>();
            paymentMap.put("id", payment.getId());
            paymentMap.put("subject", tokenPackageMap.get(payment.getPackageId()).getPackageName());
            paymentMap.put("price", tokenPackageMap.get(payment.getPackageId()).getPackagePrice());
            paymentMap.put("token", tokenPackageMap.get(payment.getPackageId()).getPackageToken());
            paymentMap.put("payNo", payment.getPayNo());
            data.add(paymentMap);
        }
        return Result.success(data);
    }


    @PostMapping("/deletePayment")
    public Result<Map<String,Object>> deletePayment(@RequestHeader("Authorization") String token, @RequestBody Payment payment){
        User user;
        try{
            user = jwtUtil.parseToken(token, User.class);
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail(CodeType.TOKEN_EXPIRED_OR_INVALID);
        }

        paymentService.deletePayment(payment);
        return Result.success();
    }


}
